import {Component, EventEmitter, Input, OnChanges, OnInit, Output, ViewChild} from '@angular/core';
import {NzFormatEmitEvent, NzTreeComponent} from 'ng-zorro-antd/tree';
import {RoleModel} from '../../../../models/role.model';
import {BaseService} from '../../../../shared/service/base.service';
import {LayerService} from '../../../../shared/service/layer.service';
import {ApiUrl} from '../../../../config/api-url';
import {Globals} from "../../../../globals";
import {PermissionPlatformTypeEnum} from "../../../../enums/permission-platform-type.enum";

@Component({
  selector: 'app-role-permission',
  templateUrl: './role-permission.component.html',
  styleUrls: ['./role-permission.component.less']
})
export class RolePermissionComponent implements OnInit, OnChanges {
  permissionPlatformTypeEnum = {
    PC_WEB_PAGE : PermissionPlatformTypeEnum.PC_WEB_PAGE,
    MERCHANT_APPLET : PermissionPlatformTypeEnum.MERCHANT_APPLET,
  };
  platformType = this.permissionPlatformTypeEnum.PC_WEB_PAGE;
  @Input()
  isVisible = false;
  @Output()
  emitVisible: EventEmitter<any> = new EventEmitter();
  nodes = [];
  isOkLoading = false;
  @ViewChild('tree', {read: NzTreeComponent, static: true})
  ngTrue: NzTreeComponent;
  @Input()
  role: RoleModel;
  //选择的节点
  selectPermissionList = [];
  //指定选中复选框的树节点
  defaultCheckedKeys = [];
  //指定选中的树节点
  defaultSelectedKeys = [];
  //展开指定的树节点
  defaultExpandedKeys = [];
  isMobile = Globals.isMobile();
  tabsIndex = 0;
  constructor(private httpService: BaseService, private layer: LayerService, public baseService: BaseService) {
  }

  ngOnInit() {
    console.info('ngOnInit...........');
    this.getPermissionList();
  }

  ngOnChanges() {
    this.tabsIndex = 0;
    this.platformType = this.permissionPlatformTypeEnum.PC_WEB_PAGE;
    this.initializeNode();
  }
  initializeNode(){
    //选择的节点
    this.selectPermissionList = [];
    //指定选中复选框的树节点
    this.defaultCheckedKeys = [];
    //展开指定的树节点
    this.defaultExpandedKeys = [];
    //渲染角色授权
    if (this.isVisible) {
      //角色已有的权限，将节点Select设为true
      this.collatingData(this.nodes);
      //根据角色渲染权限节点
      this.renderRoleAuthorize(this.nodes);
    } else {
      //nodesTree复位select为false
      this.nodesReset(this.nodes);
    }
  }
  selectedIndexChange(data){
    this.tabsIndex = data;
    if (this.tabsIndex == 0){
      this.platformType = this.permissionPlatformTypeEnum.PC_WEB_PAGE;
    } else if (this.tabsIndex == 1){
      this.platformType = this.permissionPlatformTypeEnum.MERCHANT_APPLET;
    } else {
      this.baseService.layer.notificationError("tabsIndex非法");
    }
    this.getPermissionList();
  }
  //递归复位(节点全部select为false)
  nodesReset(nodes) {
    nodes.forEach(node => {
      if (node.children != undefined) {
        this.nodesReset(node.children);
      }
      node.select = false;
    });
  }

  //角色已有的权限，将节点Select设为true
  collatingData(nodes) {
    nodes.forEach(node => {
      if (node.children != undefined) {
        this.collatingData(node.children);
      }
      this.role.permissions.forEach(permission => {
        if (permission.key == node.key) {
          node.select = true;
        }
      });
    });
  }

  handleOk(): void {
    this.isOkLoading = true;
    this.authorizeSubmit();
  }

  handleCancel(): void {
    this.isVisible = false;
    let body = {'refresh': false, 'isVisible': this.isVisible};
    this.emitVisible.emit(body);
  }

  nzEvent(event: NzFormatEmitEvent): void {
    console.log(event);
  }

  getPermissionList() {
    this.httpService.get(ApiUrl.PermissionUrl + '/list?noAuth=true&platformType=' + this.platformType).subscribe(
      data => {
        if (data.status == 0) {
          //这个递归只要就是前台展示，那些是选择，那些是没选择
          // this.renderRoleAuthorize(data.data);
          this.nodes = data.data;
          this.initializeNode();
        }
      }
    );
  }

  authorizeSubmit() {
    this.findSelectNodes();
    let url = ApiUrl.RolePermissionUrl + '/authorize?roleId=' + this.role.id + '&platformType=' + this.platformType;
    this.httpService.post(url, this.selectPermissionList).subscribe(
      data => {
        if (data.status == 0) {
          this.layer.notificationSuccess('分配权限成功');
          this.isVisible = false;
          this.isOkLoading = false;
          let body = {'refresh': true, 'isVisible': this.isVisible};
          this.emitVisible.emit(body);
        } else {
          this.layer.notificationError(data.msg);
          this.isOkLoading = false;
        }
      }
    );
  }

  findSelectNodes() {
    //半选状节点
    this.ngTrue.getHalfCheckedNodeList().forEach(node => {
      this.selectPermissionList = [...this.selectPermissionList, node.origin.id];
    });
    //选中状节点
    this.ngTrue.getCheckedNodeList().forEach(node => {
      this.selectPermissionList = [...this.selectPermissionList, node.origin.id];
      this.findNodeChildren(node.origin);
    });
  }

  //递归获取选中状子节点
  findNodeChildren(node) {
    node.children.forEach(item => {
      if (item.children) {
        this.findNodeChildren(item);
      }
      this.selectPermissionList = [...this.selectPermissionList, item.id];
    });
  }

  renderRoleAuthorize(nodes) {
    nodes.forEach(node => {
      if (node.children.length != 0) {
        this.renderRoleAuthorize(node.children);
      }
      if (node.select == true) {
        //节点为选时，屏开节点
        this.defaultExpandedKeys = [...this.defaultExpandedKeys, node.id];
        //节点没有children并select为true时，设为点击节点
        if (node.children.length == 0) {
          this.defaultCheckedKeys = [...this.defaultCheckedKeys, node.id];
        }
      }
    });
  }
}
